/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_components/zhiqim_manager.htm
 *
 * Zhiqim Manager is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.manager.presenter;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.ZmlContexts;
import org.zhiqim.httpd.context.annotation.AnIntercept;
import org.zhiqim.httpd.validate.ones.IsByteLen;
import org.zhiqim.httpd.validate.onex.IsUserPass;
import org.zhiqim.httpd.validate.two.IsEqual;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.constants.CodeConstants;
import org.zhiqim.kernel.model.maps.HashMapSO;
import org.zhiqim.kernel.model.maps.MapSO;
import org.zhiqim.kernel.json.Jsons;
import org.zhiqim.kernel.model.codes.Base64;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.kernel.util.Bytes;
import org.zhiqim.kernel.util.Ids;
import org.zhiqim.kernel.util.Randoms;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.manager.ZmrBootstrap;
import org.zhiqim.manager.ZmrPassworder;
import org.zhiqim.manager.ZmrSessionUser;
import org.zhiqim.manager.dao.ZmrOperatorDao;
import org.zhiqim.manager.dbo.ZmrAvatar;
import org.zhiqim.manager.dbo.ZmrOperator;
import org.zhiqim.manager.dbo.ZmrParamOperator;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;

/**
 * 个人中心控制器
 *
 * @version v1.0.0 @author zouzhigang 2017-6-5 新建与整理
 */
@AnAlias("ZmrProfilePresenter")
@AnIntercept("chkZmrLogin")
public class ZmrProfilePresenter implements CodeConstants
{
    /** 关闭超级管理员权限 */
    public static void doCloseSuperAdmin(HttpRequest request) throws Exception
    {
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        if (!sessionUser.isSuperAdmin())
        {
            request.setResponseError("你没有关闭超级管理员权限");
            return;
        }
        
        if (ORM.table().count(ZmrOperator.class, new Selector("operatorType", 1)) == 0)
        {
            request.setResponseError("还没有设置管理员，不能关闭超级管理员");
            return;
        }
        
        Updater updater = new Updater();
        updater.addField("operatorStatus", 1);
        updater.addMust("operatorType", 0);
        
        ORM.table().update(ZmrOperator.class, updater);
    }
    
    /**修改密码*/
    public static void doUpdatePassword(HttpRequest request) throws Exception
    {
        request.addValidate(new IsByteLen("oldPassword", "密码为6-16位，请输入正确的旧密码", 6, 16));
        request.addValidate(new IsUserPass("newPassword", "新密码不合法，要求6-16位（大小写字母数字和特殊字符必须四选三）"));
        request.addValidate(new IsUserPass("newPassword2", "新密码确认不合法，要求6-16位（大小写字母数字和特殊字符必须四选三）"));
        request.addValidate(new IsEqual("newPassword", "newPassword2", "新密码和新密码确认不一致"));
        
        if (!request.chkValidate())
        {
            request.setResponseError(request.getAlertMsg());
            return;
        }
        
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        String operatorCode = sessionUser.getOperatorCode();
        
        ZmrOperator operator = ORM.table().item(ZmrOperator.class, operatorCode);
        if(operator == null || !ZmrOperatorDao.validatePassword(request, operator, oldPassword))
        {
            request.setResponseError("旧密码不正确");
            return;
        }
        
        String newPassSalt = Randoms.lettersDigitsSecure(64);
        ZmrPassworder passworder = ZmrBootstrap.getPassworder();
        newPassword = passworder.encode(operatorCode, newPassword, newPassSalt);
        
        Updater updater = new Updater();
        updater.addMaybe("operatorCode", operatorCode);
        updater.addField("operatorPass", newPassword);
        updater.addField("operatorPassSalt", newPassSalt);
        updater.addField("operatorModified", Sqls.nowTimestamp());
        ORM.table().update(ZmrOperator.class, updater);
        
        sessionUser.setOperator(ORM.table().item(ZmrOperator.class, sessionUser.getOperatorCode()));
        
        //增加操作日志
        ZmrOperatorDao.addOperateLog(request, "操作员修改密码", Jsons.toString("operatorCode", operatorCode));
    }
    
    /** 修改手机号 */
    public static void doUpdateMobile(HttpRequest request, String mobile) throws Exception
    {
        if(!Validates.isMobile11(mobile, false))
        {
            request.setResponseError("请输入正确的手机号");
            return;
        }
        
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        
        Updater updater = new Updater();
        updater.addMust("operatorCode", sessionUser.getOperatorCode());
        updater.addField("operatorMobile", mobile);
        ORM.table().update(ZmrOperator.class, updater);
        
        sessionUser.setOperator(ORM.table().item(ZmrOperator.class, sessionUser.getOperatorCode()));
        
        //增加操作日志
        ZmrOperatorDao.addOperateLog(request, "操作员修改手机号", Jsons.toString("operatorCode", sessionUser.getOperatorCode(), "mobile", mobile));
    }
    
    /** 修改电子邮箱 */
    public static void doUpdateEmail(HttpRequest request, String email) throws Exception
    {
        if(!Validates.isEmail(email, false))
        {
            request.setResponseError("请输入正确的邮箱");
            return;
        }
        
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        Updater updater = new Updater();
        updater.addMust("operatorCode", sessionUser.getOperatorCode());
        updater.addField("operatorEmail", email);
        ORM.table().update(ZmrOperator.class, updater);
        
        sessionUser.setOperator(ORM.table().item(ZmrOperator.class, sessionUser.getOperatorCode()));
        
        //增加操作日志
        ZmrOperatorDao.addOperateLog(request, "操作员修改邮箱", Jsons.toString("operatorCode", sessionUser.getOperatorCode(), "email", email));
    }
    
    /** 查询系统头像 */
    public static String doQuerySysAvatar(HttpRequest request) throws Exception
    {
        int page = request.getParameterInt("page", 1);
        int pageSize = 18;
        
        PageResult<ZmrAvatar> result = ORM.table().page(ZmrAvatar.class, page, pageSize, new Selector("avatarType", 0).addOrderbyAsc("avatarId"));
        result.addConditionMap(request.getParameterMap());
        
        return ZmlContexts.parseZmlPath(request, "/zview/zhiqim_manager/presenter/selSysAvatarInfo.zml", "result", result);
    }
    
    /** 修改为系统头像 */
    public static void doUpdateSysAvatar(HttpRequest request, long avatarId) throws Exception
    {
        if(ORM.table().count(ZmrAvatar.class, avatarId) == 0)
        {
            request.setResponseError("选择的头像不存在，请重新选择");
            return;
        }
        
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        ZmrOperator operator = ORM.table().item(ZmrOperator.class, sessionUser.getOperatorCode());
        if (operator.getOperatorAvatar() != 0)
        {//不为0，检查是否用户自定义的
            ZmrAvatar avatar = ORM.table().item(ZmrAvatar.class, operator.getOperatorAvatar());
            if (avatar.getAvatarType() == 1)
            {//如果是，要删除自定义的数据
                ORM.table().delete(ZmrAvatar.class, operator.getOperatorAvatar());
            }
        }
        
        Updater updater = new Updater();
        updater.addMust("operatorCode", sessionUser.getOperatorCode());
        updater.addField("operatorAvatar", avatarId);
        ORM.table().update(ZmrOperator.class, updater);
        
        sessionUser.setOperator(ORM.table().item(ZmrOperator.class, sessionUser.getOperatorCode()));
        
        //增加操作日志
        ZmrOperatorDao.addOperateLog(request, "操作员修改头像", Jsons.toString("operatorCode", sessionUser.getOperatorCode(), "avatarId", avatarId));
    }
    
    /** 修改为自定义头像*/
    public static void doUpdateSelfAvatar(HttpRequest request, String data) throws Exception
    {
        //1.读取头像图片
        int idx = data.indexOf(",");
        byte[] imageData = Base64.decode(data.substring(idx+1));
        
        byte[]  bytes50 = Bytes.resizePNG(imageData, 50, 50);
        if(bytes50 == null)
        {
            request.setResponseError("图片错误");
            return;
        }
        
        byte[]  bytes100 = Bytes.resizePNG(imageData, 100, 100);
        if(bytes100 == null)
        {
            request.setResponseError("图片错误");
            return;
        }
        
        byte[]  bytes150 = Bytes.resizePNG(imageData, 150, 150);
        if(bytes150 == null)
        {
            request.setResponseError("图片错误");
            return;
        }
        
        //2.以数据库数据为准，查操作员信息，防止账号多浏览器登录
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        ZmrOperator operator = ORM.table().item(ZmrOperator.class, sessionUser.getOperatorCode());
        
        if (operator.getOperatorAvatar() != 0)
        {
            ZmrAvatar avatar = ORM.table().item(ZmrAvatar.class, operator.getOperatorAvatar());
            if (avatar.getAvatarType() == 1)
            {//操作员自定义的，要删除头像图片
                ORM.table().delete(ZmrAvatar.class, operator.getOperatorAvatar());
            }
        }
        
        //3.新的头像插入到头像表
        long avatarId = Ids.longId13();
        ZmrAvatar avatar = new ZmrAvatar();
        avatar.setAvatarId(avatarId);
        avatar.setAvatarType(1);//自定义头像
        avatar.setAvatarTime(System.currentTimeMillis());
        avatar.setAvatar50(bytes50);
        avatar.setAvatar100(bytes100);
        avatar.setAvatar150(bytes150);
        ORM.table().insert(avatar);

        //4.更新操作员头像Id号
        Updater updater = new Updater();
        updater.addMust("operatorCode", sessionUser.getOperatorCode());
        updater.addField("operatorAvatar", avatarId);
        ORM.table().update(ZmrOperator.class, updater);
        
        //5.更新会话为新的头像Id号
        operator.setOperatorAvatar(avatarId);
        sessionUser.setOperator(operator);
        
        //增加操作日志
        ZmrOperatorDao.addOperateLog(request, "操作员上传头像", Jsons.toString("operatorCode", sessionUser.getOperatorCode(), "avatarId", avatarId));
    }
    
    /** 修改参数 */
    public static void doUpdateParam(HttpRequest request) throws Exception
    {
        String paramKey = request.getParameter("paramKey");
        String paramValue = request.getParameter("paramValue");
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        
        if(ORM.table().count(ZmrParamOperator.class, paramKey) <= 0)
        {
            request.setResponseError("该操作员参数键未定义，请重新输入");
            return;
        }
        
        ZmrOperatorDao.addOrUpdateOperatorParam(request, sessionUser.getOperatorCode(), paramKey, paramValue);
        sessionUser.setOperator(ORM.table().item(ZmrOperator.class, sessionUser.getOperatorCode()));
        
        //增加操作日志
        MapSO map = new HashMapSO(3);
        map.put("operatorCode", sessionUser.getOperatorCode());
        map.put("paramKey", paramKey);
        map.put("paramValue", paramValue);
        
        ZmrOperatorDao.addOperateLog(request, "操作员修改参数", Jsons.toString(map));
    }
}
